package com.open.spring.common.exception;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.open.tools.JsonUtil;
/**
 * 
 * @ClassName：ExceptionHandler 
 * @Description：异常处理
 *         
 * @author kinter    
 * @date 2017年1月1日 下午4:38:19    
 *
 */
public class ExceptionHandler implements HandlerExceptionResolver{
	private Logger logger = Logger.getLogger(ExceptionHandler.class);
	/**
	 * 处理异常信息返回
	 */
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		long code = 10000;
		String errMessage = "系统繁忙,请稍后再试！";
	   if (ex.getClass().equals(DataAccessException.class)) {
			errMessage = "数据库操作失败！";
		} else if (ex.getClass().equals(NullPointerException.class)) {

			errMessage = "调用了未经初始化的对象或者是不存在的对象！";
		} else if (ex.getClass().equals(IOException.class)) {
			errMessage = "IO异常！";
		} else if (ex.getClass().equals(ClassNotFoundException.class)) {
			errMessage = "指定的类不存在！";
		} else if (ex.getClass().equals(ArithmeticException.class)) {
			errMessage = "数学运算异常！";
		} else if (ex.getClass().equals(ArrayIndexOutOfBoundsException.class)) {
			errMessage = "数组下标越界!";
		} else if (ex.getClass().equals(IllegalArgumentException.class)) {
			errMessage = "方法的参数错误！";
		} else if (ex.getClass().equals(ClassCastException.class)) {
			errMessage = "类型强制转换错误！";
		} else if (ex.getClass().equals(SecurityException.class)) {
			errMessage = "违背安全原则异常！";
		} else if (ex.getClass().equals(SQLException.class)) {
			errMessage = "操作数据库异常！";
		} else if (ex.getClass().equals(NoSuchMethodError.class)) {
			errMessage = "方法末找到异常！";
		} else if (ex.getClass().equals(InternalError.class)) {
			errMessage = "Java虚拟机发生了内部错误";
		}else {
			ex.printStackTrace();
			errMessage = "程序内部错误，操作失败！";
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("msg", errMessage);
		map.put("status", code);
		logger.error(ex.toString(), ex);
        try{
        	OutputStream out = response.getOutputStream();
    		response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = new PrintWriter(out);
            pw.print(JsonUtil.toJson(map));
            pw.flush();
            out.close();
        }catch(IOException e){
        	logger.error(e);
        	e.printStackTrace();
        }catch(Exception e){
        	logger.error(e);
            e.printStackTrace();
        }
		return null;
	}

}
